package com.myblog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.SysRole;
import com.myblog.model.po.SysUser;
import com.myblog.service.SysRoleService;
import com.myblog.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author
 * @since 2022-08-29
 */
@Controller
@RequestMapping("/user")
public class SysUserController {
    private static final String HTML_PREFIX = "system/user/";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping(value = {"/", ""})
    @PreAuthorize("hasAuthority('sys:user')")
    public String user() {
        return HTML_PREFIX + "user-list";
    }

    @GetMapping(value = {"/form","/form/{id}"})
    @PreAuthorize("hasAnyAuthority('sys:user:add','sys:user:edit')")
    public String form(@PathVariable(required = false)Long id, Model model) {
        SysUser sysUser = sysUserService.findById(id);
        model.addAttribute("user",sysUser);
        //还要查出所有的角色信息
        List<SysRole> sysRoleList = sysRoleService.list();
        model.addAttribute("roleListAll",sysRoleList);
        return HTML_PREFIX + "user-form";
    }

//    /**
//     * 返回值为200则有权限
//     * @param id
//     * @return
//     */
//    @GetMapping("/{id}")
//    @PostAuthorize("returnObject.code==200")
//    public ResultInfoFactory deleteById(@PathVariable Long id) {
//        return ResultInfoFactory.success();
//    }
//
//    @GetMapping("/batch/{ids}")// -1,0,1,2
//    @PreFilter(filterTarget = "ids",value = "filterObject > 0")
//    public ResultInfoFactory deleteByIds(@PathVariable List<Long> ids) {
//        return ResultInfoFactory.success();
//    }

    @PreAuthorize("hasAuthority('sys:user:list')")
    @PostMapping("/page")
    @ResponseBody
    public ResultInfoFactory page(Page<SysUser> page,SysUser sysUser){
        return ResultInfoFactory.success(sysUserService.selectPage(page, sysUser));
    }


    @PreAuthorize("hasAnyAuthority('sys:user:add','sys:user:edit')")
    @RequestMapping(value = "saveOrUpdate",method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(SysUser sysUser){
        sysUserService.saveOrUpdate(sysUser);
        return "redirect:/user";
    }

    @PreAuthorize("hasAuthority('sys:user:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable Long id){
        //伪删除
        sysUserService.deleteByUserId(id);
        return ResultInfoFactory.success();
    }

}
